/**
 *
 * @constructor
 */
$(document).ready(function () {
    Reservation.Action.managerInit();
    Reservation.Action.managerRun();
})
Reservation.memo = {
    entityName: "entityName",
    platforms: "platforms",
    "locations": "locations",
    "reservation": "reservation",
    "saveData": "saveData",
    "editData": "editData",
    "delData": "delData",
    "reservationStatus": "reservationStatus",
    "broadcastTask": "broadcastTask",
    getChannel:"getChannel"
};
Reservation.Action = (function () {
    var infoNewDivInit = false;
    var batchResponseDivInit = false;
    var infoDetailDivInit = false;
    var infoEditDivInit = false;

    function managerInit() {
        $("#navDiv").tabs();
        $("#infoNewDiv").dialog({
            title: "创建预约",
            autoOpen: false,
            width: 840,
            modal: true,
            dialogClass: 'alert',
            resizable: false,
            open: function () {
                if (!infoNewDivInit) {
                    $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    var $button = $("#infoNewDiv").parent().find(".ui-dialog-titlebar-close")
                    $button.bind("click", function (event) {
                        Reservation.Templete.initModifyForm()

                    })
                    infoNewDivInit = true;
                }

            }
        });

        $("#batchResponseDiv").dialog({
            title: "回应",
            autoOpen: false,
            width: 440,
            modal: true,
            dialogClass: 'alert',
            resizable: false,
            open: function () {
                if (batchResponseDivInit) {
                    return;
                }
                batchResponseDivInit = true;
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            close: function () {
                $("#infoNewDiv").dialog("open");
            }
        })
        $("#infoDetailDiv").dialog({
            title: "预约明细",
            autoOpen: false,
            width: 440,
            modal: true,
            dialogClass: 'alert',
            resizable: false,
            open: function () {
                if (infoDetailDivInit) {
                    return;
                }
                infoDetailDivInit = true;
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            }
        });
        $("#infoEditDiv").dialog({
            title: "预约修改",
            autoOpen: false,
            width: 840,
            modal: true,
            dialogClass: 'alert',
            resizable: false,
            open: function () {
                if (infoEditDivInit) {
                    return;
                }
                infoEditDivInit = true;
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            }
        })

        $("#list").jqGrid({
            ajaxGridOptions: {
                beforeSend: function (request) {
                    request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                }
            },
            mtype: "get",
            datatype: "json",
            height: 450,
            caption: "预约列表",
            colNames: Reservation.Grid.colNames,
            colModel: Reservation.Grid.colModel,
            jsonReader: Reservation.Grid.jsonReader,
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            pager: "#pager"
        })
    }

    function managerRun() {

        var channelId = Com.url.getParameter("id");
        if (channelId == null) {
            return;
        }
        var taskArr = [];
        taskArr.push(Reservation.Task.getChannel(parseInt(channelId)));
        taskArr.push(Reservation.Task.broadcastTask(parseInt(channelId)));
        taskArr.push(Reservation.Task.locationsTask());
        taskArr.push(Reservation.Task.platformsTask());
        $.each(taskArr, function (index, element) {
            Reservation.ajaxManager.push(element.regName, element.options);
        })

        var task = Reservation.Task.reservationStatusTask();
        Reservation.ajaxManager.push(task.regName, null, task.responseData);

        Reservation.ajaxManager.afterLoadComplete(function () {
            Reservation.Task.initComplete();
        });
        Reservation.ajaxManager.startLoad();
    }

    return {
        managerInit: managerInit,
        managerRun: managerRun
    }
})()

Reservation.Validate = (function () {
    var regForNum = /^\d+$/;
    var regForTime = /^\d{2}:\d{2}:\d{2}$/;
    var regForDate = /^\d{4}-\d{2}-\d{2}$/;
    var regForDateTime = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;

    function checkNum(checkString) {
        return regForNum.test(checkString)
    }

    function checkTime(checkString) {
        return regForTime.test(checkString)
    }

    function checkDate(checkString) {
        return regForDate.test(checkString)
    }

    function checkDateTime(checkString) {
        return regForDateTime.test(checkString)
    }

    function checkForReservation(entity, checkDateTimeFlag) {
        if (!checkNum($.trim(entity.delayTime))) {
            Reservation.util.showTips({
                content: "PC网页端延时输入正整数"
            })
            return false;
        }
        if (!checkNum(entity.opsStatus)) {
            Reservation.util.showTips({
                content: "上下线状态错误"
            })
            return false;
        }
        if (checkDateTimeFlag) {
            if (!checkDate(entity.startDay) || !checkDate(entity.endDay)) {
                Reservation.util.showTips({
                    content: "日期格式错误"
                })
                return false;
            }
            if (!checkTime(entity.startTime) || !checkTime(entity.endTime)) {
                Reservation.util.showTips({
                    content: "时间格式错误"
                })
                return false;
            }
        }
        entity.delayTime = parseInt($.trim(entity.delayTime));
        entity.opsStatus = parseInt($.trim(entity.opsStatus));
        return true;
    }

    function checkForChangeName(entity, checkDateTimeFlag) {
        if ($.trim(entity.channelName).length == 0) {
            Reservation.util.showTips({
                content: "新名字不能为空字符"
            })
            return false;
        }

        if ($.trim(entity.channelName).length > 40) {
            Reservation.util.showTips({
                content: "新名字有效长度不能超过40"
            })
            return false;
        }
        if (checkDateTimeFlag) {
            if (!checkDate(entity.startDay) || !checkDate(entity.endDay)) {
                Reservation.util.showTips({
                    content: "日期格式错误"
                })
                return false;
            }
            if (!checkTime(entity.startTime) || !checkTime(entity.endTime)) {
                Reservation.util.showTips({
                    content: "时间格式错误"
                })
                return false;
            }
        }
        entity.channelName = $.trim(entity.channelName);
        return true;
    }

    return {
        checkNum: checkNum,
        checkForReservation: checkForReservation,
        checkForChangeName: checkForChangeName
    }
})()
Reservation.Templete = (function () {
    function makePlatformList() {
        var htmlArr = [];
        htmlArr.push('<div><label>操作端：</label>（勾选后针对操作端预约）</div>')
        htmlArr.push('<div><label><input type="checkbox" value="-1" name="client_mainAll" >全选</label></div>')
        htmlArr.push('<div><div>')
        var responseData = Reservation.Dao.getPlatforms();
        var resultArr = responseData.data;
        $.each(resultArr, function (index, element) {
            htmlArr.push('<span><label style="width:150px"><input type="checkbox"  value="' + element.key + '" name="client" >' + element.descr + '</label></span>');
            if ((index + 1) % 5 == 0) {
                htmlArr.push("</div><div>");
            }
        });
        htmlArr.push('</div></div>');
        return htmlArr.join("");
    }


    function showSelectLocation(backListStr) {
        var htmlArr = [];
        htmlArr.push('<div><label>地域黑名单</label></div>')
        if (backListStr == null || $.trim(backListStr).length == 0) {
            htmlArr.push("<div>无</div>")
        } else {
            var backList = backListStr.split(",");
            var countLocation = 0;
            htmlArr.push('<div><div>')
            $.each(backList, function (index, element) {
                var dataArr = element.split("_")
                htmlArr.push('<span><label style="width:120px">' + dataArr[2] + '</label></span>');
                countLocation++;
                if (countLocation % 5 == 0) {
                    htmlArr.push("</div><div>");
                }
            });
            htmlArr.push("</div>");
        }
        return htmlArr.join("");
    }

    function makeBlackList() {
        var htmlArr = [];
        htmlArr.push('<div class="control-group"><span>地域黑名单</span> </div>')
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<label class="checkbox inline"><input type="checkbox" name="area_select" value="3_95_香港,3_148_澳门,3_228_台湾,6_301_海外">海外地区限制：香港、澳门、台湾、海外</label>');
        //htmlArr.push('<label class="checkbox inline"><input type="checkbox" name="area_select" value="3_2_上海,3_1_北京,4_3001_广东省广州市,4_3003_广东省深圳市">一线城市限制：上海、北京、广州、深圳</label>');
        htmlArr.push('<label class="checkbox inline"><input type="checkbox" name="area_select" value="3_2_上海,3_1_北京,4_3001_广州,4_3003_深圳">一线城市限制：上海、北京、广州、深圳</label>');
        htmlArr.push('<label class="checkbox inline"><input type="checkbox" name="area_select" value="3_1_北京,3_4_天津">京津地区限制：北京、天津</label>');
        htmlArr.push('</div>');
        htmlArr.push('<div  class="control-group"><span>自定义地域限制</span>');
        htmlArr.push('<input type="text" class="inline" name="localSuggest" placeholder="输入地区关键字检索" autocomplete="off">');
        htmlArr.push('</div>');
        htmlArr.push('<div  class="control-group"><span>地域展现控制：</span><label class="checkbox inline"><input type="checkbox" name="regionRejectSearch" value="0" >屏蔽搜索</label></div>');

        return htmlArr.join("");
    }

    function makeBtnZone(assignLabel) {
        var htmlArr = [];
        htmlArr.push('<div class="controls" style="margin-top: 20px" align="center">')
        htmlArr.push('<input type="button" name="dialogSave" class="btn" value="' + assignLabel + '">')
        htmlArr.push("&nbsp;&nbsp;&nbsp;&nbsp;")
        htmlArr.push('<input type="button" name="dialogCloseBtn" class="btn" value="关闭">')
        htmlArr.push('</div>')
        return htmlArr.join("");
    }

    function searchZone() {
        var htmlArr = [];
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>展现控制：</span><label class="checkbox inline"><input type="checkbox" name="rejectSearch" value="0" >屏蔽搜索</label>');
        htmlArr.push('</div>');
        return htmlArr.join("");
    }


    function makeReservationZone() {
        var htmlArr = [];
        var regName = "reservation_zone0";
        htmlArr.push('<div name="' + regName + '" class="form-inline">')
        htmlArr.push('<div align="center">提示：请先到“播控中心”创建直播控制，再添加“预约计划”</div>')
        htmlArr.push(makePlatformList())
        htmlArr.push(dateZone())
        htmlArr.push(onlineStatusZone());
        htmlArr.push(searchZone())
        htmlArr.push(reservationDelayZone(regName));
        htmlArr.push(makeBlackList());
        htmlArr.push(makeBtnZone("保存播控"));
        htmlArr.push("</div>")
        return htmlArr.join("");
    }

    function makeChangeNameZone() {
        var htmlArr = [];
        var regName = "reservation_changeName";
        htmlArr.push('<div name="' + regName + '" class="form-inline">')
        htmlArr.push(dateZone())
        htmlArr.push("<div><span>频道更名为：</span><input type='text' name='newChannelName'></div>");
        htmlArr.push(makeBtnZone("保存频道更名"));
        htmlArr.push("</div>")
        return htmlArr.join("");
    }

    function dateZone() {
        var htmlArr = [];
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>开始日期：</span>');
        htmlArr.push('<input type="text" class="input-small" name="startDay" >');
        htmlArr.push('\t<span>结束日期：</span>');
        htmlArr.push('<input type="text" class="input-small" name="endDay" >');
        htmlArr.push('</div>');
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>开始时间：</span>');
        htmlArr.push('<input type="text" class="input-small" name="onLineTime" value="00:00:00" >');
        htmlArr.push('\t<span>结束时间：</span>');
        htmlArr.push('<input type="text" class="input-small" name="offLineTime" value="23:59:59" >');
        htmlArr.push('</div>');
        return htmlArr.join("");
    }

    function onlineStatusZone() {
        var htmlArr = [];
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>上下线状态：</span>');
        htmlArr.push('<input type="radio" name="online_status" value="1"><span>上线</span>');
        htmlArr.push('<input type="radio" name="online_status" value="2"><span>下线</span>');
        htmlArr.push('</div>');
        return htmlArr.join("");
    }

    function reservationDelayZone(regName) {
        var htmlArr = [];
        var channelEntity = Reservation.Dao.getChannel()
        //   if(channelEntity.liveType == 2){
               htmlArr.push('<div class="control-group" style="display:none">');
        //   }else{
         //   htmlArr.push('<div class="control-group">');
        //   }
        htmlArr.push('<span>PC网页端延时：</span><input  name="' + regName + '_delay" type="text" value="0"> 秒');
        htmlArr.push('</div>');
        return htmlArr.join("");
    }

    function makeChangeNameDetailZone(rowObj) {
        var htmlArr = [];
        htmlArr.push('<div class="form-inline">')
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>开始时间：</span>' + rowObj.startTime);
        htmlArr.push('</div>');
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>结束时间：</span>' + rowObj.endTime);
        htmlArr.push('</div>');
        htmlArr.push("<div><span>频道更名为：</span>" + rowObj.blacklist + "</div>");
        htmlArr.push("</div>");
        return htmlArr.join("");
    }


    function makeReservationDetailZone(rowObj) {
        var htmlArr = [];
        htmlArr.push('<div class="form-inline">')
        htmlArr.push(showSelectClient(rowObj.platform))
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>开始时间：</span>' + rowObj.startTime);
        htmlArr.push('</div>');
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>结束时间：</span>' + rowObj.endTime);
        htmlArr.push('</div>');
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>上下线状态：</span>' + (rowObj.opsStatus == 1 ? "上线" : "下线"));
        htmlArr.push('</div>');
        var channelEntity = Reservation.Dao.getChannel()
        //   if(channelEntity.liveType == 2){
        //        htmlArr.push('<div class="control-group" style="display:none">');
        //   }else{
            htmlArr.push('<div class="control-group">');
        //   }

        htmlArr.push('<span>PC网页端延时：</span>' + rowObj.delayTime + '秒');
        htmlArr.push('</div>');
        htmlArr.push(showSelectLocation(rowObj.blacklist));
        if (rowObj.rejectSearch == 1) {
            htmlArr.push('<div class="control-group">平台屏蔽搜索</div>');
        }
        if (rowObj.regionRejectSearch == 1) {
            htmlArr.push('<div class="control-group">地域屏蔽搜索</div>');
        }
        htmlArr.push("</div>");
        return htmlArr.join("");
    }

    function showSelectClient(clientId) {
        var clientName = null;
        var responseData = Reservation.Dao.getPlatforms();
        var resultArr = responseData.data;
        $.each(resultArr, function (index, element) {
            if (element.key == clientId) {
                clientName = element.descr;
                return true;
            }
        })
        return '<div><label>操作端：</label>' + clientName + '</div>';
    }

    function editChangeName() {
        var htmlArr = [];
        htmlArr.push('<div class="form-inline">')
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>开始时间：</span><label name="editStartTime"></label>');
        htmlArr.push('</div>');
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>结束时间：</span><label name="editEndTime"></label>');
        htmlArr.push('</div>');
        htmlArr.push("<div><span>频道更名为：</span><input type='text' name='newChannelName'></div>");
        htmlArr.push("</div>");
        return htmlArr.join("");
    }

    function editReservation() {
        var htmlArr = [];
        htmlArr.push('<div class="form-inline">')
        htmlArr.push('<div><label>操作端：</label><label name="editClientName"></label></div>');
        // htmlArr.push(showSelectClient(rowObj.platform))
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>开始时间：</span><label name="editStartTime"></label>');
        htmlArr.push('</div>');
        htmlArr.push('<div class="control-group">');
        htmlArr.push('<span>结束时间：</span><label name="editEndTime"></label>');
        htmlArr.push('</div>');
        htmlArr.push(onlineStatusZone());
        htmlArr.push(searchZone())
        htmlArr.push(reservationDelayZone("reservation"));
        htmlArr.push(makeBlackList());
        htmlArr.push("</div>");
        return htmlArr.join("");
    }

    function initModifyForm() {
        $("form[name=modifyForm]")[0].reset();
        $("input[name=startDay]").datepicker("option", "maxDate", null);
        $("input[name=endDay]").datepicker("option", "minDate", null);
        $("input[name=onLineTime]").timepicker("option", "maxDateTime", null);
        $("input[name=offLineTime]").timepicker("option", "minDateTime", null);
        $("input[name=onLineTime]").val("00:00:00");
        $("input[name=offLineTime]").val("23:59:59");
        $("#tabPanel0").find("input[name$=delay]").removeAttr("disabled");
        var suggestInput = $("#tabPanel0").find("input[name=localSuggest]");
        suggestInput.removeAttr("data-id")
        var spans = $("#tabPanel0").find("span .tagmanagerTag")
        console.log("spans legnth" + spans.length);
        $("#tabPanel0").find("span .tagmanagerTag").remove();
    }

    return {
        makeChangeNameZone: makeChangeNameZone,
        makeReservationZone: makeReservationZone,
        makeChangeNameDetailZone: makeChangeNameDetailZone,
        makeReservationDetailZone: makeReservationDetailZone,
        editChangeName: editChangeName,
        editReservation: editReservation,
        initModifyForm: initModifyForm
    }

})()
Reservation.Task = (function () {

    function getChannel(fatherId) {
        return {
            regName: Reservation.memo.getChannel,
            options: {
                type: "post",
                url: Reservation.urlConfig.channelGet,
                dataType: "json",
                data: {id: fatherId}
            }
        }
    }

    function broadcastTask(channelId) {
        return {
            regName: Reservation.memo.broadcastTask,
            options: {
                url: Reservation.urlConfig.getBroadcastControls,
                type: "get",
                dataType: "json",
                data: {channelId: channelId}
            }
        }
    }

    function locationsTask() {
        return {
            regName: Reservation.memo.locations,
            options: {
                url: Reservation.urlConfig.configs,
                type: "get",
                data: {type: "Location"},
                dataType: "json"
            }
        }
    }

    function platformsTask() {
        return {
            regName: Reservation.memo.platforms,
            options: {
                url: Reservation.urlConfig.configs,
                type: "get",
                data: {type: "PlayPlatform"},
                dataType: "json"
            }
        }
    }

    function reservationStatusTask() {
        return {
            regName: Reservation.memo.reservationStatus,
            // 1 等待中 2 生效失败 3 生效成功 4 还原失败 5 还原成功 9 删除
            responseData: {
                code: "A00000",
                data: [
                    {"key": 1, "descr": "等待中"},
                    {"key": 2, "descr": "生效失败"},
                    {"key": 3, "descr": "生效成功"},
                    {"key": 4, "descr": "还原失败"},
                    {"key": 5, "descr": "还原成功"}
                ]
            }
        }
    }

    function reservationDelTask() {
        return {
            regName: Reservation.memo.delData,
            options: {
                url: Reservation.urlConfig.reservationDel,
                type: "post",
                dataType: "json"
            }
        }
    }

    function reservationEditTask() {
        return {
            regName: Reservation.memo.editData,
            options: {
                url: Reservation.urlConfig.reservationEdit,
                type: "post",
                dataType: "json",
                success: function (data) {
                    Reservation.util.showTips({
                        content: data.msg
                    })
                    if (data.code == "A00000") {
                        $("#list").trigger("reloadGrid");
                    } else {
                        $("#infoEditDiv").dialog("open")
                    }
                },
                error: function (data) {
                    Reservation.util.showTips({
                        content: "修改失败"
                    })
                    $("#infoEditDiv").dialog("open")
                }
            }
        }
    }

    function reservationCreateTask() {
        return {
            regName: Reservation.memo.saveData,
            options: {
                url: Reservation.urlConfig.reservationCreate,
                type: "post",
                dataType: "json"
            },
            handler: function (options) {
                console.log(options.acceptArr);
                var responseArr = [];
                var platformsData = Reservation.Dao.getPlatforms();
                $.each(options.acceptArr, function (index, element) {
                    if (element.operationSuccess == false) {
                        var originData = options.originalArr[ element.nodeIndex ]
                        if (originData["channelName"] != null) {
                            responseArr.push("<div><b>频道更名</b>发生错误：<span style='color: red'>" + element.msg + "</span></div>");
                        } else {
                            var platformName = null;
                            var resultArr = platformsData.data;
                            $.each(resultArr, function (index, platform) {
                                if (platform.key == originData.platform) {
                                    platformName = platform.descr;
                                    return true;
                                }
                            })
                            responseArr.push("<div><b>" + platformName + "</b>发生错误：<span style='color: red'>" + element.msg + "</span></div>");
                        }
                    }
                });
                if (responseArr.length > 0) {
                    $("#batchResponseDiv").html(responseArr.join(""));
                    $("#batchResponseDiv").dialog("open");
                    if (options.originalArr.length > responseArr.length) {
                        $("#list").trigger("reloadGrid");
                    }
                } else {
                    Reservation.Templete.initModifyForm();
                    $("#list").trigger("reloadGrid");
                }
            }
        }
    }

    function submitSave() {
        var $showTabPanel = $("div[aria-hidden=false]");
        var tabPanelName = $showTabPanel.attr("id")
        console.log("current" + tabPanelName);
        var dataArr = null;
        var task = reservationCreateTask();
        var entity = null;
        if (tabPanelName == "tabPanel0") {
            var selectClientResult = $showTabPanel.find("input[name=client]:checked");
            if (selectClientResult.length == 0) {
                Reservation.util.showTips({
                    content: "至少选择一个操作端"
                })
                $("#infoNewDiv").dialog("open");
                return;
            }
            entity = getReservationData()
            if (!Reservation.Validate.checkForReservation(entity, true)) {
                $("#infoNewDiv").dialog("open");
                return;
            }
            dataArr = syncToClientArr(entity);
        } else if (tabPanelName == "tabPanel1") {
            entity = getChangeChannelNameData();
            if (!Reservation.Validate.checkForChangeName(entity, true)) {
                $("#infoNewDiv").dialog("open");
                return;
            }
            dataArr = [entity]
        }
        Reservation.ajaxManager.batchRequest(task.regName, task.options, dataArr, task.handler);
        Reservation.ajaxManager.startLoad();
    }

    function submitEdit() {
        var containDiv = $("#infoEditDiv");
        var id = containDiv.find("input[name=modifyId]").val();
        var type = containDiv.find("input[name=type]").val();
        var entityData = {};
        entityData.id = parseInt(id);
        if (type == 1) {
            entityData.delayTime = containDiv.find("input[name$=delay]").val();
            entityData.opsStatus = containDiv.find("input[type=radio]:checked").val();
            entityData.rejectSearch = containDiv.find("input[name=rejectSearch]").prop("checked") == true ? 1 : 0;
            entityData.regionRejectSearch = containDiv.find("input[name=regionRejectSearch]").prop("checked") == true ? 1 : 0;
            var saveBlackList = [];
            var locationResult = containDiv.find(".tagmanagerTag")
            $.each(locationResult, function (index, blackLocation) {
                saveBlackList.push(blackLocation.getAttribute("data-tag-id") + "_" + blackLocation.getAttribute("data-tag-label"))
            })
            entityData.blacklist = saveBlackList.join(",");
            if (!(Reservation.Validate.checkForReservation(entityData))) {
                containDiv.dialog("open");
                return;
            }
        } else {
            entityData.channelName = containDiv.find("input[name=newChannelName]").val();
            if (!(Reservation.Validate.checkForChangeName(entityData))) {
                containDiv.dialog("open");
                return;
            }
        }
        var task = reservationEditTask();
        task.options.data = entityData;
        Reservation.ajaxManager.push(task.regName, task.options, null, true);
        Reservation.ajaxManager.startLoad();
    }

    function getChangeChannelNameData() {
        var $showTabPanel = $("div[aria-hidden=false]");
        var onLineTime = $showTabPanel.find("input[name=onLineTime]").val();
        var offLineTime = $showTabPanel.find("input[name=offLineTime]").val();
        var startDay = $showTabPanel.find("input[name=startDay]").val();
        var endDay = $showTabPanel.find("input[name=endDay]").val();

        var channelName = $showTabPanel.find("input[name=newChannelName]").val();
        var entityData = Reservation.Dao.entityChangeName();
        entityData.channelId = Com.url.getParameter("id");
        entityData.channelName = channelName;
        entityData.startTime = onLineTime; //hh:mm:ss
        entityData.endTime = offLineTime; //hh:mm:ss
        entityData.startDay = startDay; //2014-01-01
        entityData.endDay = endDay;
        return entityData;
    }

    function getReservationData() {
        var saveBlackList = [];
        var $showTabPanel = $("div[aria-hidden=false]");
        var locationResult = $showTabPanel.find(".tagmanagerTag")
        $.each(locationResult, function (index, obj) {
            saveBlackList.push(obj.getAttribute("data-tag-id") + "_" + obj.getAttribute("data-tag-label"))
        })

        var onlineValue = $showTabPanel.find("input[type=radio]:checked").val();
        var delayValue = $showTabPanel.find("input[name$=delay]").val();
        var onLineTime = $showTabPanel.find("input[name=onLineTime]").val();
        var offLineTime = $showTabPanel.find("input[name=offLineTime]").val();
        var startDay = $showTabPanel.find("input[name=startDay]").val();
        var endDay = $showTabPanel.find("input[name=endDay]").val();
        var blackList = saveBlackList.join(",");
        var entityData = Reservation.Dao.entityReservation()
        var rejectSearchValue = $showTabPanel.find("input[name=rejectSearch]").prop("checked") == true ? 1 : 0;
        var regionRejectSearchValue = $showTabPanel.find("input[name=regionRejectSearch]").prop("checked") == true ? 1 : 0;
        entityData.channelId = Com.url.getParameter("id");
        entityData.platform = 0;
        entityData.delayTime = delayValue;
        entityData.blacklist = blackList;
        entityData.opsStatus = onlineValue;
        entityData.startTime = onLineTime; //hh:mm:ss
        entityData.endTime = offLineTime; //hh:mm:ss
        entityData.startDay = startDay; //2014-01-01
        entityData.endDay = endDay;
        entityData.rejectSearch = rejectSearchValue;
        entityData.reason = "";
        entityData.regionRejectSearch = regionRejectSearchValue;
        return entityData;
    }

    function syncToClientArr(entity) {
        var reservationArr = [];
        var $showTabPanel = $("div[aria-hidden=false]");
        var selectClientResult = $showTabPanel.find("input[name=client]:checked");
        $.each(selectClientResult, function (index, client) {
            var entityData = Reservation.Dao.entityReservation()
            entityData.channelId = entity.channelId;
            entityData.platform = parseInt(client.value);
            entityData.delayTime = entity.delayTime;
            entityData.blacklist = entity.blacklist;
            entityData.opsStatus = entity.opsStatus;
            entityData.startTime = entity.startTime;
            entityData.endTime = entity.endTime;
            entityData.startDay = entity.startDay;
            entityData.endDay = entity.endDay;
            entityData.reason = entity.reason;
            entityData.rejectSearch = entity.rejectSearch;
            entityData.regionRejectSearch = entity.regionRejectSearch;
            reservationArr.push(entityData);
        })
        return reservationArr;
    }

    function initEnableClient() {
        var broadcastData = Reservation.Dao.getBroadcast()
        var clientArr = $("#tabPanel0").find("input[name=client]");
        var enableClientArr = [];
        $.each(broadcastData.data, function (index, clientAble) {
            enableClientArr.push(clientAble.platform + "");
        })
        $.each(clientArr, function (index, client) {
            $(client).prop("disabled", "disabled");
            if (enableClientArr.indexOf($(client).val()) != -1) {
                $(client).removeAttr("disabled");
            }
        });
    }

    function initNewField() {
        $("#tabPanel0").html(Reservation.Templete.makeReservationZone())
        $("#tabPanel1").html(Reservation.Templete.makeChangeNameZone())
    }

    function initEditField() {
        $("#editField_2").html(Reservation.Templete.editChangeName());
        $("#editField_1").html(Reservation.Templete.editReservation());
    }


    function initSuggest() {
        $("input[name=localSuggest]").suggest({
            source: Reservation.urlConfig.redirect,
            parseValue: function () {
                var self = this;
                var val = this.element.val(),
                    ret = [],
                    items = null,
                    itemData = null,
                    options = self.options;

                if (val) {
                    items = val.split(',');
                    $.each(
                        items, function (i, item) {
                            item = item.split('_');
                            itemData = {};
                            itemData[options.labelKey] = fixLocaltion(item[2]);
                            itemData[options.valueKey] = item[0] + "_" + item[1];
                            ret.push(itemData);
                        }
                    );
                }
                this._value('');
                return ret;
            },
            process: function (json) {
                var ret = [],
                    self = this,
                    options = self.options,
                    itemData = null;
                var data = null;
                if (json.code === "A00000") {
                    data = $.isArray(json) ? json : json.data;
                }
                if (!data) {
                    return [];
                }
                $.map(data, function (item) {
                    itemData = {};
                    itemData[options.valueKey] = item["type"] + "_" + item["code"];
                    itemData[options.labelKey] = item["originalName"];
                    //  itemData["name"] = item["name"]
                    ret.push(itemData);
                });
                return ret;
            },
            method: "post",
            getParam: function (owner, term) {
                var requestData = {url: Reservation.Constant.third_location_url, type: "get", params: {word: this.element.val()}};
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },
            template: function (item) {
                return '<div class="contract-item" >' + item.label + '</div>';
            }
        });
    }


    function bindClickHandler() {
        $("input[name$=mainAll]").click(function (event) {
            var parentTarget = $(event.target).parent().parent().parent()
            var checkedFlag = $(event.target).prop("checked") == true;
            var childName = event.currentTarget.name.split("_")[0];
            if (checkedFlag) {
                parentTarget.find("input[name=" + childName + "]:enabled").prop("checked", true);
            } else {
                parentTarget.find("input[name=" + childName + "]:enabled").removeAttr("checked");
            }
        })

        $("input[name=area_select]").click(function (event) {
            var jObj = $(event.currentTarget.parentNode.parentNode);
            var child = $(event.currentTarget);
            var selectArr = formatToLocationItem(child.val());
            var suggestInput = jObj.parent().find("input[name=localSuggest]");
            if (child.prop("checked") == true) {
                for (var i = 0; i < selectArr.length; i++) {
                    suggestInput.suggest("addValue", selectArr[i]);
                }
            } else {
                for (var i = 0; i < selectArr.length; i++) {
                    var el = suggestInput.parent().find("span[data-tag-id=" + selectArr[i].id + "]").find("a");
                    if (el.length > 0) {
                        suggestInput.suggest("removeValue", el);
                    }
                }
            }
        })

        $("input[name=startDay]").datepicker({
            onClose: function (selectedDate) {
                $(this).parent().find("input[name=endDay]").datepicker("option", "minDate", selectedDate);

            }
        });
        $("input[name=endDay]").datepicker({
            onClose: function (selectedDate) {
                $(this).parent().find("input[name=startDay]").datepicker("option", "maxDate", selectedDate);
            }
        });
        $("input[name=onLineTime]").timepicker({

            onClose: function (selectedDate) {
                var toDate = new Date();
                var dataArr = selectedDate.split(":");
                var checkLength = dataArr.length
                switch (checkLength) {
                    case 3:
                        toDate.setSeconds(parseInt(dataArr[2]));
                    case 2:
                        toDate.setMinutes(parseInt(dataArr[1]));
                    case 1:
                        toDate.setHours(parseInt(dataArr[0]));
                }
                if (checkLength > 0) {
                    var $showTabPanel = $("div[aria-hidden=false]");
                    var offLineField = $showTabPanel.find("input[name=offLineTime]")
                    offLineField.timepicker("option", "minDateTime", toDate);
                    if (offLineField.val() == "") {
                        offLineField.val("23:59:59")
                    }
                }
            }
        });
        $("input[name=offLineTime]").timepicker({

            onClose: function (selectedDate) {
                var toDate = new Date();
                var dataArr = selectedDate.split(":");
                var checkLength = dataArr.length
                switch (checkLength) {
                    case 3:
                        toDate.setSeconds(parseInt(dataArr[2]));
                    case 2:
                        toDate.setMinutes(parseInt(dataArr[1]));
                    case 1:
                        toDate.setHours(parseInt(dataArr[0]));
                }
                if (checkLength > 0) {
                    var $showTabPanel = $("div[aria-hidden=false]");
                    var onLineField = $showTabPanel.find("input[name=onLineTime]")
                    onLineField.timepicker("option", "maxDateTime", toDate);
                    if (onLineField.val() == "") {
                        onLineField.val("00:00:00")
                    }
                }
            }
        });

        $("input[name=online_status]").click(function (event) {
            var delayField = $("#tabPanel0").find("input[name$=delay]")
            if (event.currentTarget.value == "1") {
                delayField.removeAttr("disabled");
            } else {
                delayField.prop("disabled", "disabled");
            }
        })

        $("input[name=createBtn]").click(function (event) {
            $("#infoNewDiv").dialog("open")
        })
        $("input[name=dialogCloseBtn]").click(function (event) {
            Reservation.Templete.initModifyForm();
            $("#infoNewDiv").dialog("close")
        })
        $("input[name=dialogCloseBtn2]").click(function (event) {
            $("#infoDetailDiv").dialog("close")
        })
        $("input[name=dialogSave]").click(function (event) {
            $("#infoNewDiv").dialog("close")
            Reservation.Task.submitSave();
        })

        $("input[name=dialogEditBtn]").click(function (event) {
            $("#infoEditDiv").dialog("close")
            Reservation.Task.submitEdit()
        })
    }

    function initComplete() {

        console.log("init end");
        $("input[name=startDate]").datetimepicker({

                sliderAccessArgs: { touchonly: false },
                onClose: function (selectedDate) {
                    $("input[name=endDate]").datetimepicker("option", "minDate", selectedDate);
                    var toDate = new Date(selectedDate.replace(/-/g, "/"))
                    $("input[name=endDate]").datetimepicker("option", "minDateTime", toDate);
                }
            }
        );
        $("input[name=endDate]").datetimepicker({

            sliderAccessArgs: { touchonly: false },
            onClose: function (selectedDate) {
                $("input[name=startDate]").datetimepicker("option", "maxDate", selectedDate);
                var toDate = new Date(selectedDate.replace(/-/g, "/"))
                $("input[name=startDate]").datetimepicker("option", "maxDateTime", toDate);
            }
        });

        Reservation.memo.id = Com.url.getParameter("id");
        if (Reservation.memo.id == null) {
            Reservation.util.showTips({
                content: "没有频道Id",
                type: "error"
            })
            $("form[name=basicFrm]").submit(function () {
                return false;
            })
            return;
        }
        $("form[name=basicFrm]").submit(function () {
            console.log("start query");
            try {
                var sendObj = {};
                sendObj.startTime = $("input[name=startDate]").val()
                sendObj.endTime = $("input[name=endDate]").val()
                sendObj.pageSize = 40;
                sendObj.channelId = Reservation.memo.id
                // sendObj.platform = 0;
                sendObj.status = $("select[name=status]").val();
                $("#list").setGridParam({postData: sendObj}).trigger("reloadGrid");
            } catch (error) {
                console.error(error);
            } finally {
                return false;
            }
        })

        initNewField();
        initEditField()
        bindClickHandler();
        initEnableClient();
        initSuggest();
        var responseData = Reservation.Dao.getReservationStatus();
        var htmls = []
        htmls.push('<option value="">全部</option>')
        $.each(responseData.data, function (index, obj) {
            htmls.push('<option value="' + obj.key + '">' + obj.descr + '</option>')
        })
        $("select[name=status]").html(htmls.join(""))
        $("#list").setGridParam({url: Reservation.Grid.queryUrl, postData: {channelId: Reservation.memo.id, pageSize: 40}}).trigger("reloadGrid");
    }

    return {
        broadcastTask: broadcastTask,
        locationsTask: locationsTask,
        platformsTask: platformsTask,
        getChannel: getChannel,
        reservationStatusTask: reservationStatusTask,
        initComplete: initComplete,
        reservationDelTask: reservationDelTask,
        submitSave: submitSave,
        submitEdit: submitEdit
    }
})()
Reservation.Formatter = (function () {
    function statusDescr(statusType) {
        var responseData = Reservation.Dao.getReservationStatus();
        var ret = "未找到状态：" + statusType;
        $.each(responseData.data, function (index, obj) {
            if (statusType == obj.key) {
                ret = obj.descr;
                return true;
            }
        })
        return ret;
    }

    function platformDesc(obj) {
        if (obj.type == 2) {
            return "全端";
        }
        var platformKey = obj.platform
        var responseData = Reservation.Dao.getPlatforms();
        var ret = "未找到平台编号：" + platformKey;
        $.each(responseData.data, function (index, obj) {
            if (platformKey == obj.key) {
                ret = obj.descr;
                return true;
            }
        })
        return ret;
    }

    function gridOptions(rowObject) {
        var responseData = Reservation.Dao.getReservationStatus();
        var htmls = [];
        htmls.push("<a onclick='Reservation.Grid.viewObj(" + JSON.stringify(rowObject) + ")'>查看</a>");
        if (rowObject.status == 1) {
            htmls.push("<a onclick='Reservation.Grid.modifyObj(" + JSON.stringify(rowObject) + ")'>修改</a>");
            htmls.push("<a onclick='Reservation.Grid.delRow(" + rowObject.id + ")'>删除</a>");
        }

        return htmls.join(" ")
    }

    function onlineStatusDescr(onlineStatus) {
        return onlineStatus == 1 ? "上线" : "下线";
    }

    return {
        statusDescr: statusDescr,
        platformDesc: platformDesc,
        gridOptions: gridOptions,
        onlineStatusDescr: onlineStatusDescr
    }
})()
Reservation.Dao = (function () {
    function getDataByName(targetName) {
        var responseData = Reservation.ajaxManager.findResponseData(targetName);
        return responseData;
    }

    function getBroadcast() {
        return getDataByName(Reservation.memo.broadcastTask)
    }

    function getPlatforms() {
        return getDataByName(Reservation.memo.platforms);
    }

    function getChannel() {
        return getDataByName(Reservation.memo.getChannel).data;
    }

    function getReservationStatus() {
        return getDataByName(Reservation.memo.reservationStatus);
    }

    function entityReservation() {
        var entity = {};
        entity.channelId = 0;
        entity.platform = 0;
        entity.startTime = ""; //hh:mm:ss
        entity.endTime = ""; //hh:mm:ss
        entity.startDay = ""; //2014-01-01
        entity.endDay = "";
        entity.delayTime = 0;
        entity.blacklist = "";
        entity.opsStatus = 0; //1,2
        entity.reason = "";
        entity.rejectSearch = 0;
        entity.regionRejectSearch = 0;
        return entity;
    }

    function entityChangeName() {
        var entity = {};
        entity.channelId = 0;
        entity.channelName = "";
        entity.startTime = ""; //hh:mm:ss
        entity.endTime = ""; //hh:mm:ss
        entity.startDay = ""; //2014-01-01
        entity.endDay = "";
        entity.reason = "";
        return entity;
    }

    return {
        getBroadcast: getBroadcast,
        entityReservation: entityReservation,
        entityChangeName: entityChangeName,
        getPlatforms: getPlatforms,
        getReservationStatus: getReservationStatus,
        getChannel:getChannel
    }
})()
Reservation.Grid = (function () {
    var colNames = [ "开始时间", "结束时间", "上下线状态", "类型", "操作端", "状态", "操作时间", "操作"];
    var colModel = [

        {
            name: "startTime",
            index: 'startTime',
            title: false,
            width: 120,
            sortable: false,
            align: "center"
        },
        {
            name: "endTime",
            index: 'endTime',
            title: false,
            width: 120,
            sortable: false,
            align: "center"
        },
//        {
//            name: "delayTime",
//            index: 'delayTime',
//            title: false,
//            width: 120,
//            sortable: false,
//            align: "center",
//            hidden: true
//        },
        {
            name: "opsStatus",
            index: 'opsStatus',
            title: false,
            width: 120,
            sortable: false,
            align: "center",
            hidden: true,
            formatter: function (cellvalue, options, rowObject) {
                return Reservation.Formatter.onlineStatusDescr(cellvalue);
            }
        },
        {
            name: "type",
            index: 'type',
            align: "center",
            title: false, sortable: false,
            formatter: function (cellvalue, options, rowObject) {
                if (cellvalue != null) {
                    return cellvalue == 1 ? "播控" : "频道更名"
                }
                return ""
            }
        },
        {
            name: "platform",
            index: 'platform',
            title: false,
            width: 120,
            sortable: false,
            align: "center",
            formatter: function (cellvalue, options, rowObject) {
                return Reservation.Formatter.platformDesc(rowObject);
            }
        },
        {
            name: "status",
            index: 'status',
            title: false,
            width: 120,
            sortable: false,
            align: "center",
            formatter: function (cellvalue, options, rowObject) {
                return Reservation.Formatter.statusDescr(cellvalue);
            }
        },
        {
            name: "addTime",
            index: 'addTime',
            title: false,
            width: 120,
            sortable: false,
            align: "center"
        },
        {
            index: 'options',
            title: false,
            width: 120,
            sortable: false,
            align: "center",
            formatter: function (cellvalue, options, rowObject) {
                return  Reservation.Formatter.gridOptions(rowObject)
            }
        }

    ]
    var jsonReader = {
        root: "data.data",
        page: "data.page.pageNo",
        records: "data.page.totalCount",
        id: "id"
    };

    function delRow(objId) {
        auth.getAuthData({tips: 1, url: '/epg/reservation_delete.html'}, function (rt) {
            if (rt) {
                $(document).tips({
                    content: '很抱歉，您没有删除的权限!'
                });
                return;
            }
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    var task = Reservation.Task.reservationDelTask();
                    $.ajax({
                        url: task.options.url,
                        dataType: task.options.dataType,
                        data: {id: objId},
                        beforeSend: function (request) {
                            request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                        },
                        type: task.options.type,
                        success: function (data) {
                            Reservation.util.showTips({
                                content: data.msg
                            })
                            if (data.code == "A00000") {
                                $("#list").trigger("reloadGrid")
                            }
                        }
                    })
                }
            })
        });
    }

    function modifyObj(obj) {
        var containDiv = $("#infoEditDiv");
        containDiv.find("input[name=modifyId]").val(obj.id);
        containDiv.find("input[name=type]").val(obj.type);
        $("#editField_2").hide();
        $("#editField_1").hide();
        if (obj.type == 2) {
            containDiv.dialog("option", "width", 440);
            $("#editField_2").find("label[name=editStartTime]").html(obj.startTime);
            $("#editField_2").find("label[name=editEndTime]").html(obj.endTime);
            $("#editField_2").find("input[name=newChannelName]").val(obj.blacklist);
            $("#editField_2").show();
        } else if (obj.type == 1) {
            containDiv.dialog("option", "width", 840)
            $("#editField_1").find("label[name=editClientName]").html(getClientName(obj.platform));
            $("#editField_1").find("label[name=editStartTime]").html(obj.startTime);
            $("#editField_1").find("label[name=editEndTime]").html(obj.endTime);
            $("#editField_1").show();
            containDiv.find("input[name$=delay]").val(obj.delayTime);
            var radioValue = obj.opsStatus == 1 ? 1 : 2;
            containDiv.find("input[type=radio][value=" + radioValue + "]").prop("checked", true);
            if (obj.rejectSearch == 1) {
                containDiv.find("input[name=rejectSearch]").prop("checked", true)
            } else {
                containDiv.find("input[name=rejectSearch]").removeAttr("checked");
            }
            if (obj.regionRejectSearch == 1) {
                containDiv.find("input[name=regionRejectSearch]").prop("checked", true)
            } else {
                containDiv.find("input[name=regionRejectSearch]").removeAttr("checked");
            }
            if (obj.blacklist != null && obj.blacklist.length) {
                var selectArr = formatToLocationItem(obj.blacklist);
                var suggestInput = $("#editField_1").find("input[name=localSuggest]");
                for (var i = 0; i < selectArr.length; i++) {
                    suggestInput.suggest("addValue", selectArr[i]);
                }
            }
        }
        containDiv.dialog("open");
    }

    function getClientName(clientId) {
        var clientName = null;
        var responseData = Reservation.Dao.getPlatforms();
        var resultArr = responseData.data;
        $.each(resultArr, function (index, element) {
            if (element.key == clientId) {
                clientName = element.descr;
                return true;
            }
        })
        return clientName;
    }

    function viewObj(obj) {
        if (obj.type == 2) {
            $("#detailField").html(Reservation.Templete.makeChangeNameDetailZone(obj));
        } else if (obj.type == 1) {
            $("#detailField").html(Reservation.Templete.makeReservationDetailZone(obj));
        }

        $("#infoDetailDiv").dialog("open");
    }

    return {
        colNames: colNames,
        colModel: colModel,
        queryUrl: Reservation.urlConfig.reservationGet,
        jsonReader: jsonReader,
        delRow: delRow,
        viewObj: viewObj,
        modifyObj: modifyObj
    }
})();

function fixLocaltion(originValue) {
    var regFixLocaltion = /^\W*省|市$/g;
    if (originValue == null) {
        return "";
    }
    return originValue.replace(regFixLocaltion, "");
}
function formatToLocationItem(inputStr) {
    var ret = [];
    var items = inputStr.split(",")

    $.each(
        items, function (i, item) {
            item = item.split('_');
            var itemData = {};
            itemData["label"] = fixLocaltion(item[2]);
            itemData["id"] = item[0] + "_" + item[1];
            ret.push(itemData);
        }
    );
    return ret;
}


